package com.sunny.structure.queue;

import java.util.Stack;

/**
 * 两个栈实现队列
 *
 * @author Sunny
 * @date 2020/6/23
 */
public class TwoStackOneQueue {
    private Stack<Integer> stackPush;
    private Stack<Integer> stackPop;

    public TwoStackOneQueue(Stack<Integer> stackPush, Stack<Integer> stackPop) {
        this.stackPush = stackPush;
        this.stackPop = stackPop;
    }

    /**
     * 进栈
     *
     * @param value 值
     */
    public void add(Integer value) {
        stackPush.add(value);
    }

    /**
     * 弹栈
     */
    public Integer poll() {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new RuntimeException("queue isEmpty!");
        }else if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    /**
     * 获取队首元素
     */
    public Integer peek() {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new RuntimeException("queue isEmpty!");
        }else if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }

    public static void main(String[] args) {
        TwoStackOneQueue queue = new TwoStackOneQueue(new Stack<Integer>(), new Stack<Integer>());
        queue.add(1);
        queue.add(2);
        queue.add(3);

        System.out.println(queue.peek());

        System.out.println(queue.poll());

        System.out.println(queue.peek());
        System.out.println(queue.peek());

        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }
}
